<?php

/**
 * This is the model class for table "credits".
 *
 * The followings are the available columns in table 'credits':
 * @property integer $id
 * @property integer $client_id
 * @property integer $user_id
 * @property integer $shop_id
 * @property string $product_name
 * @property string $receipt_date
 * @property integer $duration
 * @property string $close_date
 * @property string $created_at
 * @property string $updated_at
 * @property float $scorring_ball
 * @property integer $status
 */
class Credits extends CActiveRecord
{
	public $client_fio;

	const SCORRING_LIMIT = 5; //минимальное значение скорринга для положительного результата

	const STATUS_DENY = 0; //отказано
	const STATUS_SUCCESS = 1; //одобрено
	const STATUS_CLOSED = 2; //погашен
	const STATUS_SCORRING = 3; //в обработке скоринга
	const STATUS_NEW_SCORRING = 4; //получены свежие данные по скоррингу

	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return Credits the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{credits}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('client_id, user_id, shop_id, sum, product_name, duration, created_at', 'required'),
			array('client_id, user_id, shop_id, duration, status', 'numerical', 'integerOnly'=>true),
			array('sum, scorring_ball', 'numerical'),
			array('product_name', 'length', 'max'=>250),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, client_id, user_id, shop_id, sum, product_name, receipt_date, duration, close_date, created_at, updated_at, scorring_ball, status, client_fio', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'shops' => array(self::BELONGS_TO, 'Shops', 'shop_id'),
			'client'=> array(self::BELONGS_TO, 'Clients', 'client_id'),
			'repayments' => array(self::HAS_MANY, 'Repayments', 'credit_id'),
			'repaymentsSum' => array(self::STAT, 'Repayments', 'credit_id', 'select'=> 'SUM(sum)'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'Номер договора',
			'client_id' => 'Client',
			'user_id' => 'User',
			'shop_id' => 'shop_id',
			'sum' => 'Сумма',
			'product_name' => 'Наименование товара',
			'receipt_date' => 'Дата получения',
			'duration' => 'Срок (дней)',
			'close_date' => 'Дата погашения',
			'created_at' => 'Составлен',
			'updated_at' => 'Обновлена',
			'scorring_ball' => 'Scorring',
			'status' => 'Статус',
		);
	}

	public function getEndDays()
	{
		// Осталось до окончания договора
		$end = strtotime($this->receipt_date.' + '.$this->duration.' day');
		return round(($end-time())/(24*60*60));
	}

	public function afterFind()
	{
		parent::afterFind();
		$this->client_fio = $this->client->surname.' '.$this->client->name.' '.$this->client->patronymic;
		return true;
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->with = array('client','shops');

		$criteria->compare('id',$this->id);
		$criteria->compare('client_id',$this->client_id);
		$criteria->compare('user_id',$this->user_id);
		$criteria->compare('shop_id',$this->shop_id);
		$criteria->compare('product_name',$this->product_name,true);
		$criteria->compare('receipt_date',$this->receipt_date,true);
		$criteria->compare('duration',$this->duration);
		$criteria->compare('close_date',$this->close_date,true);
		$criteria->compare('created_at',$this->created_at,true);
		$criteria->compare('updated_at',$this->updated_at,true);
		$criteria->compare('scorring_ball',$this->scorring_ball,true);
		$criteria->compare('status',$this->status);

		$criteria->compare('CONCAT_WS(" ",client.surname,client.name,client.patronymic)', $this->client_fio, true);

		if(Yii::app()->user->getState('role')==Users::MANAGER_ROLE){
			$criteria->compare('shops.organization_id',Yii::app()->user->getState('organization_id'));
		}

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
			'sort'=>array(
				'defaultOrder'=>'t.id DESC',
				'attributes'=>array(
					'client_fio'=>array(
						'asc'=>'client_fio',
						'desc'=>'client_fio DESC',
					),
					'*',
				),

			),
			'pagination'=>array(
				'pageSize'=>20,
			),
		));
	}

	public static function getCredits($organization_id=null,$client_id=null)
	{
		$criteria = new CDbCriteria();
		$criteria->with = 'shops';

		/*$criteria->select = 't.*, sum({{repayments}}.sum) as repaymentsSum';
		$criteria->join = 'LEFT JOIN {{repayments}} ON {{repayments}}.credit_id = t.id';
		$criteria->group = 't.id';*/

		if($organization_id)
			$criteria->compare('shops.organization_id', $organization_id);

		if($client_id)
			$criteria->compare('client_id', $client_id);

		$sort = new CSort();
		$sort->attributes = array(
			/*'repaymentsSum'=>array(
				'asc'=>'repaymentsSum',
				'desc'=>'repaymentsSum DESC',
			),*/
			'*'
		);
		$sort->defaultOrder = 'created_at';

		return new CActiveDataProvider(self::model(), array(
			'criteria' => $criteria,
			'sort'=> $sort,
			'pagination'=>array(
				'pageSize'=>100,
			),
		));
	}

	public function getRepayments()
	{
		$criteria = new CDbCriteria();
		$criteria->compare('credit_id',$this->id);

		return new CActiveDataProvider('Repayments',array(
			'criteria'=>$criteria,
			'sort'=>array('defaultOrder'=>'created_at DESC'),
			'pagination'=>array(
				'pageSize'=>100,
			),
		));
	}

	public static function getStatusName($id)
	{
		$statuses = array(
			Credits::STATUS_SCORRING => '<span class="label label-inverse">В обработке</span>',
			Credits::STATUS_SUCCESS  => '<span class="label label-success">Одобрено</span>',
			Credits::STATUS_DENY  => '<span class="label label-important">Отказано</span>',
			Credits::STATUS_CLOSED  => '<span class="label label-info">Погашено</span>',
			Credits::STATUS_NEW_SCORRING  => '<span class="label label-warning">Получен</span>'
		);

		return isset($statuses[$id])?$statuses[$id]:'Не определен';
	}

	public static function getStatusesList()
	{
		return array(
			Credits::STATUS_SCORRING 	  => 'В обработке',
			Credits::STATUS_SUCCESS  	  => 'Одобрено',
			Credits::STATUS_DENY  		  => 'Отказано',
			Credits::STATUS_CLOSED 		  => 'Погашено',
			Credits::STATUS_NEW_SCORRING  => 'Получен'
		);
	}

	public function CreditsNew()
	{
		$criteria = new CDbCriteria();
		$criteria->compare('status', self::STATUS_SCORRING);
		$criteria->compare('status', self::STATUS_NEW_SCORRING, false, 'OR');
		$criteria->compare('user_id', Yii::app()->user->id);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
			'pagination'=>array(
				'pageSize'=>100,
			),
		));
	}

	/**
	 * по полученному скоррингу с главного сервера, определям
	 * можно ли выдавать рассрочку или нет
	 */
	public function newStatus()
	{
		if ($this->scorring_ball >= Credits::SCORRING_LIMIT){
			$this->status = Credits::STATUS_SUCCESS;
			$this->receipt_date = date('Y-m-d H:i:s');
		}else{
			$this->status = Credits::STATUS_DENY;
			$this->receipt_date = null;
		}

		$this->save();
	}
}